<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="msg"></p>
    <button onclick="insertOneData()">插入一条数据</button>
    <button onclick="queryDataByPrimaryKey()">查询一条数据</button>

    <script>
        const dbName='myDB'//数据库名称
        const dbVersion=1//数据库版本
        let db;
        function connectToDatabase(){
            const request = indexedDB.open(dbName,dbVersion)
            request.onupgradeneeded=(e)=>{
                db=e.target.result
                if(!db.objectStoreNames.contains('user')){
                    db.createObjectStore('user',{keyPath:'id'})
                }

            }

            request.onsuccess=(e)=>{
                db=e.target.result
                document.getElementById('msg').innerHTML='数据库连接成功'
            }

        }
        connectToDatabase()

        function insertOneData(){
            const transaction=db.transaction(['user'],'readwrite')//创建事务(表)readwrite可读可写
            .objectStore('user')
            .add({
                id:1,
                name:'张三',
                age:18
            })
            transaction.oncomplete=()=>{
                console.log('插入成功')
            }

        }

        function queryDataByPrimaryKey(){
            const transaction=db.transaction(['user'],'readonly')//创建事务(表)readonly只读
            .objectStore('user')
            .get(1)//根据主键查询

            transaction.onsuccess=(e)=>{
                if(e.target.result){
                    console.log(e.target.result)
                }else{
                    console.log('未查询到数据')
                }
            }
        }

    </script>

</body>
</html>